import { login, logout, getInfo, refreshtoken } from '@/api/user';
import { router } from '@/router';
import storage from '@/utils/storage';
const userStore: any = {
    namespaced: true,
    state: () => {
        return {
            token: storage.get('token'),
            name: '',
            avatar: '',
            introduction: '',
            roles: [],
            permissions: [],
            permisaction: [],
        };
    },

    mutations: {
        SET_TOKEN: (state: any, token: string) => {
            state.token = token;
        },
        SET_INTRODUCTION: (state: any, introduction: any) => {
            state.introduction = introduction;
        },
        SET_NAME: (state: any, name: string) => {
            state.name = name;
        },
        SET_AVATAR: (state: any, avatar: string) => {
            if (avatar.indexOf('http') !== -1) {
                state.avatar = avatar;
            } else {
                state.avatar = process.env.VUE_APP_BASE_API + avatar;
            }
        },
        SET_ROLES: (state: any, roles: any) => {
            state.roles = roles;
        },
        SET_PERMISSIONS: (state: any, permisaction: any) => {
            state.permisaction = permisaction;
        },
    },

    actions: {
        // user login
        login({ commit }: any, userInfo: any) {
            return new Promise((resolve, reject) => {
                login(userInfo)
                    .then((response: any) => {
                        const { token } = response;
                        commit('SET_TOKEN', token);
                        storage.set('token', token);
                        resolve(token);
                    })
                    .catch((error: any) => {
                        reject(error);
                    });
            });
        },

        // get user info
        getInfo({ commit, state }: any) {
            return new Promise((resolve, reject) => {
                getInfo()
                    .then((response: any) => {
                        if (!response || !response.data) {
                            commit('SET_TOKEN', '');
                            storage.remove('token');
                            resolve('');
                        }

                        const {
                            roles,
                            name,
                            avatar,
                            introduction,
                            permissions,
                        } = response.data;

                        // roles must be a non-empty array
                        if (!roles || roles.length <= 0) {
                            reject('getInfo: roles must be a non-null array!');
                        }
                        commit('SET_PERMISSIONS', permissions);
                        commit('SET_ROLES', roles);
                        commit('SET_NAME', name);
                        commit('SET_AVATAR', avatar);
                        commit('SET_INTRODUCTION', introduction);
                        resolve(response);
                    })
                    .catch((error: any) => {
                        reject(error);
                    });
            });
        },
        // 退出系统
        LogOut({ commit, state }: any) {
            return new Promise((resolve, reject) => {
                logout()
                    .then(() => {
                        commit('SET_TOKEN', '');
                        commit('SET_ROLES', []);
                        commit('SET_PERMISSIONS', []);
                        storage.clear();
                        resolve('');
                    })
                    .catch((error: any) => {
                        reject(error);
                    });
            });
        },
        // 刷新token
        refreshToken({ commit, state }: any) {
            return new Promise((resolve, reject) => {
                refreshtoken({ token: state.token })
                    .then((response: any) => {
                        const { token } = response;
                        commit('SET_TOKEN', token);
                        storage.set('token', token);
                        resolve('');
                    })
                    .catch((error: any) => {
                        reject(error);
                    });
            });
        },

        // remove token
        resetToken({ commit }: any) {
            return new Promise((resolve) => {
                commit('SET_TOKEN', '');
                storage.remove('token');
                resolve('');
            });
        },

        // dynamically modify permissions
        changeRoles({ commit, dispatch }: any, role: any) {
            // eslint-disable-next-line no-async-promise-executor
            return new Promise(async (resolve) => {
                const token = role + '-token';
                commit('SET_TOKEN', token);
                storage.set('token', token);
                const { roles } = await dispatch('getInfo');
                // resetRouter();
                // generate accessible routes map based on roles
                const accessRoutes = await dispatch(
                    'permission/generateRoutes',
                    roles,
                    { root: true }
                );
                // dynamically add accessible routes
                router.addRoute(accessRoutes);
                // reset visited views and cached views
                dispatch('tagsView/delAllViews', null, { root: true });
                resolve('');
            });
        },
    },
};

export default userStore;
